<?php
/**
 * Created by PhpStorm.
 * User: ma
 * Date: 2017/12/20
 * Time: 18:33
 */

namespace app\admin\controller;


use app\common\model\AgentArea as AgentAreaModel;
use app\common\model\AgentArea;
use app\common\model\Area as AreaModel;
use app\common\model\Agents as AgentsModel;
use app\common\model\AgentManage as AgentManageModel;
use app\common\model\CashWith as CashWithModel;
use app\common\model\Roles;
use think\Db;
use think\model\Collection;

class Agents extends Base
{
    /**
     * 代理商首页
     */
    public  function  index(){

        $searchDetail=$this->request->param('searchDetail');

//        isset($request['searchDetail'])?$searchDetail=$request['searchDetail']:false;
//        $model=new AgentsModel();
//        $model2=new AgentManageModel();
        if(isset($searchDetail)){
//            var_dump($searchDetail);die;
            $res=\db('agent_manage')
                ->alias('am')
                ->leftJoin('agents aa','aa.age_agent_manage=am.agem_id')
                ->where('agem_phone','like',$searchDetail.'%')
                ->where('aa.age_level',0)
                ->field('age_id,age_username,age_level,age_phone,age_gender,age_agent_manage,age_create_time,age_login_time,age_status,agem_id,agem_shop_max,agem_phone,agem_email,agem_create_time,agem_status,agem_account,agem_brokerage,agem_province,agem_city,agem_region,agem_address,agem_principals,agem_number')
                ->paginate(10,false,[
                'path'=>url('agents/index',['searchDetail'=>$searchDetail])
            ]);

            $res2=$res->count();

        }else{
            $res=\db('agent_manage')
                ->alias('am')
                ->leftJoin('agents aa','aa.age_agent_manage=am.agem_id')
                ->where('aa.age_level',0)
                ->field('age_id,age_username,age_level,age_phone,age_gender,age_agent_manage,age_create_time,age_login_time,age_status,agem_id,agem_shop_max,agem_phone,agem_email,agem_create_time,agem_status,agem_account,agem_brokerage,agem_province,agem_city,agem_region,agem_address,agem_principals,agem_number')
                ->paginate(10,false,[
                'path'=>url('agents/index',['searchDetail'=>$searchDetail])
            ]);
            $res2=$res->count();
        }
        $page=$res->render();

        $this->assign('page',$page);
        $this->assign('searchDetail',$searchDetail);
        $this->assign('list',$res);
        $this->assign('count',$res2);

        return $this->fetch('agents/index');
    }
    /**
     * 代理商新增
     */
    public  function  add(){
        $model=new AreaModel();
        //获取省
        $province = $model->where(array('pid'=>0,'level'=>1))->select();
        $this->assign('province',$province);
        return $this->fetch('agents/add');
    }

    /**
     * 代理商新增处理
     */
    public  function  addDo(){
        $max =Db::name('agent_manage')->max('agem_id');
        $request=$this->request->param();
        $role = Roles::where('role_type','agent')->where('role_auth_id','all')->find();
        $data1['age_username']=$request['age_username'];
        $data1['age_password']=encrypt($request['age_password']);
        $data1['age_gender']=$request['age_gender'];
        $data1['age_create_time']=time();
        $data1['age_level']=0;
        $data1['age_status']=1;
        $data1['age_role']=$role['role_id'];
        $data2['agem_shop_max']=$request['agem_shop_max'];
        $data2['agem_principals']=$request['agem_principals'];
        $data2['agem_phone']=$request['agem_phone'];
        $data2['agem_email']=$request['agem_email'];
        $data2['agem_province']=$request['province'];
        $data2['agem_city']=$request['city'];
        $data2['agem_region']=$request['region'];
        $data2['agem_address']=$request['address'];
        $data2['agem_create_time']=time();
        $data2['agem_number']='L'.str_pad(($max+1),7,'0',STR_PAD_LEFT );

        $model=new AgentsModel();
        $model2=new AgentManageModel();
        Db::startTrans();
        try{
            $res2=$model2->data($data2)->save();
            $id=$model2->agem_id;
            $data1['age_agent_manage']=$id;
            $res=$model->data($data1)->save();
            Db::commit();

        }catch (\Exception $e){
            Db::rollback();
            $this->error('新增失败');
            return;
        }
        $this->create_log('添加代理'.$data2['agem_number'],$this->request->url());//管理日志
        $this->success('新增成功','agents/index');
    }
    /**
     * 代理商验证是否已存在
     */
    public  function  addAjax(){
        $request=$this->request->param();

            $model=new AgentsModel();
            $res=$model->where('age_username',$request["age_username"])->find();
            $res2=$res->age_username;

            if(empty($res2)){
                $return=false;

            }else{
                $return=true;

            }
//            $this->ajaxReturn($return);
        return json_encode($return);
    }
    /**
     * 代理商详情页也是修改页
     */
    public  function  update($agem_id=null){


        $model=new AreaModel();
        //获取省
        $province = $model->where(array('pid'=>0,'level'=>1))->select();
        $this->assign('province',$province);
        $res=\db('agent_manage')
            ->alias('am')
            ->leftJoin('agents as','am.agem_id=as.age_agent_manage')
            ->where('agem_id',$agem_id)
            ->find();

        $pr=$model->where('id',$res['agem_province'])->field('id,name')->find();
        $ci=$model->where('id',$res['agem_city'])->field('id,name')->find();
        $re=$model->where('id',$res['agem_region'])->field('id,name')->find();
        $this->assign('list',$res);
        $this->assign('pr',$pr);
        $this->assign('ci',$ci);
        $this->assign('re',$re);

        return $this->fetch('agents/update');
    }
    /**
     * 代理商修改处理
     */
    public  function  updateDo(){
        $request=$this->request->param();
        $data1['age_gender']=$request['age_gender'];
//        $data1['age_agent_manage']=$request['agem_id'];
        $data2['agem_id']=$request['agem_id'];
        $data2['agem_shop_max']=$request['agem_shop_max'];
        $data2['agem_principals']=$request['agem_principals'];
        $data2['agem_phone']=$request['agem_phone'];
        $data2['agem_email']=$request['agem_email'];
        $data2['agem_province']=$request['province'];
        $data2['agem_city']=$request['city'];
        $data2['agem_region']=$request['region'];
        $data2['agem_address']=$request['address'];


        $model=new AgentsModel();
        $model2=new AgentManageModel();
        Db::startTrans();
        try{
            $res2=$model2->isUpdate(true)->save($data2,['agem_id'=>$request['agem_id']]);
            $res=$model->isUpdate(true)->save($data1,['age_agent_manage'=>$request['agem_id']]);
            Db::commit();

        }catch (\Exception $e){
            Db::rollback();
            $this->error('修改失败');
            return;
        }
        $this->success('修改成功','agents/index');
    }
    /**
     * 代理商详情页
     */
    public  function  detail($agem_id=null){


        $model=new AreaModel();
        //获取省
        $province = $model->where(array('pid'=>0,'level'=>1))->select();
        $this->assign('province',$province);
        $res=\db('agent_manage')
            ->alias('am')
            ->leftJoin('agents as','am.agem_id=as.age_agent_manage')
            ->where('agem_id',$agem_id)
            ->find();

        $pr=$model->where('id',$res['agem_province'])->field('id,name')->find();
        $ci=$model->where('id',$res['agem_city'])->field('id,name')->find();
        $re=$model->where('id',$res['agem_region'])->field('id,name')->find();
        $this->assign('list',$res);
        $this->assign('pr',$pr);
        $this->assign('ci',$ci);
        $this->assign('re',$re);
        return $this->fetch('agents/detail');
    }
    /**
     * 代理商删除
     */
    public  function  delete(){
        $request = $this->request->param();
        $return = ['status' => 0, 'msg' => '参数错误', 'result' => ''];//初始化返回信息
        if ($request['act'] == 'del') {
            $res=AgentManageModel::destroy($request['agem_id']);
            if ($res !== false) {
                $this->create_log('删除代理',$this->request->url());//管理日志
                $return = ['status' => 1, 'msg' => '删除成功', 'result' => ''];
            } else {
                $return = ['status' => 0, 'msg' => '删除失败，数据库未响应', 'result' => ''];
            }
        }
        $this->ajaxReturn($return);
    }

    public function ajaxReturn($data,$type = 'json'){
        exit(json_encode($data));
    }
    /**
     * 代理商导出
     */
    public function export_agents(){
        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">代理商ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">代理账户</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">代理负责人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">代理区域</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">代理商户</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">累计收入</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">邮箱地址</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">代理电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">账户余额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">代理上限</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">注册时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">登录时间</td>';
        $strTable .= '</tr>';
        $count =\db('agent_manage')
            ->alias('ae')
            ->leftJoin('agents as','ae.agem_id=as.age_agent_manage')
            ->where('age_level',0)
            ->count();
        $p = ceil($count/5000);
        for($i=0;$i<$p;$i++){
            $start = $i*5000;
            $end = ($i+1)*5000;
            $agentsList = \db('agent_manage')
                ->alias('ae')
                ->leftJoin('agents as','ae.agem_id=as.age_agent_manage')
                ->where('age_level',0)
                ->order('agem_id')
                ->limit($start.','.$end)
                ->select();


                foreach($agentsList as $k=>$val){
                    $strTable .= '<tr>';
                    $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['agem_id'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['age_username'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['agem_principals'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.'点击查看'.' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'."查看商户".'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['agem_brokerage'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['agem_email'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['agem_phone'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['agem_account'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['agem_shop_max'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i',$val['agem_create_time']).'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i',$val['age_login_time']).'</td>';
                    $strTable .= '</tr>';
                }
                unset($agentsList);
        }
        $strTable .='</table>';
        downloadExcel($strTable,'agents_'.$i);
        exit();
    }

    /**
     * 获取地区
     */
    public function getRegion(){
        $data=array();
        $request=$this->request->param();
        $data['pid'] = $request['parent_id'];
        $data['level'] = $request['level'];
        $type = $this->request->get('type');
        if($type == 1){
            if($data['level'] == 3){
                 $area = AgentArea::field('agea_area')->select();
                 $area = array_column(json_decode(json_encode($area),true),'agea_area');
                $array =  implode(",",$area);
            }else{
                $array = "0";
            }
            $model=new AreaModel();
            $data = $model->where($data)->where('id not in('.$array.')')->select();
        }else{
            $model=new AreaModel();
            $data = $model->where($data)->select();
        }
        $html = '';
        if($data){
            foreach($data as $h){
//                if($h['id'] == $){
//                    $html .= "<option value='{$h['id']}' selected>{$h['name']}</option>";
//                }
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
        }
        return $html;
    }
    /**
     * 获取代理商代理的地区
     */
    public function getAgentRegion(){
        $request=$this->request->param();
        $id = $request['id'];
        $data=\db('agent_area')
            ->alias('aa')
            ->leftJoin('area ar','aa.agea_area=ar.id')
            ->field('merger_name,name')
            ->where('agea_agent_manage',$id)->select();

        $html = '';
        if($data){
            $html .= "<ul>";
//            $html .= "<option value=''>查看</option>";
            foreach($data as $h){

                $html .= "<li >{$h['merger_name']}</li>";
            }
            $html .= "</ul>";
        }else{
            $html.="暂时未分配商户";
        }
        return $html;
    }
    /**
     * 给代理商分配权限
     */
    public function permitAllocation(){
        $request=$this->request;
        if($request->isGet()){
            $id=$request->param('agem_id');
            $model2=new  AgentsModel();
            $res=$model2->where('age_agent_manage',$id)->find();
            $model=new AreaModel();
            //获取代理商已代理区域
            $area=\db('agent_area')
                ->alias('ata')
                ->leftJoin('area aa','ata.agea_area=aa.id')
                ->where('agea_agent_manage',$id)
                ->field('agea_agent_manage,agea_area,merger_name')
                ->select();
            //获取省
            $province = $model->where(array('pid'=>0,'level'=>1))->select();
            $this->assign('province',$province);
            $this->assign('id',$id);
            $this->assign('res',$res);
            $this->assign('area',$area);
            return $this->fetch('permitAllocation');
        }elseif ($request->isPost()){
            $data['agea_area']=$request->param('region');
            $model= new  AgentAreaModel();
            $data2=$model->where('agea_area',$data['agea_area'])->find();
            if(!empty($data2)){
                $this->error('分配失败，该区域已有代理商');
                die;
            }
            $data['agea_agent_manage']=$request->param('id');
            $data['agea_create_time']=time();
            $res=$model->data($data)->save();
            if($res){
                $this->success('分配成功','agents/index');
            }else{
                $this->error('分配失败');
            }
        }

    }

    /**
     * 代理商代理区域删除
     */
    public  function  areaDelete(){
        $request = $this->request->param();
//        $return = ['status' => 0, 'msg' => '参数错误', 'result' => ''];//初始化返回信息
        $data['agea_agent_manage']=$request['agem_id'];
        $data['agea_area']=$request['agea_area'];
//        return $data;
            $model=new AgentAreaModel();
            $res=$model->where($data)->delete();
            if ($res !== false) {
                $return = ['status' => 1, 'msg' => '删除成功', 'result' => ''];
            } else {
                $return = ['status' => 0, 'msg' => '删除失败，数据库未响应', 'result' => ''];
            }

        $this->ajaxReturn($return);
//        return $this->redirect('agent/index');
    }
    /**
     * 代理商提现
     */
    public  function  getCash(){

        $searchDetail=$this->request;
        $start_time=$searchDetail->param('start_time');
        $end_time=$searchDetail->param('end_time');
        $status=$searchDetail->param('status');
        $user_id=$searchDetail->param('user_id');
        $realname=$searchDetail->param('realname');
        $bank_card=$searchDetail->param('bank_card');
        if($searchDetail->isPost()){
            $data=$searchDetail->post();
            $data['start_time']=strtotime($data['start_time']);
            $data['end_time']=strtotime($data['end_time']);
            $where[] = [ ['c_status', '=', $data['status']],['label', '=', 3],['agent_id', '>', 0]];
            $where2[]=[['agem_id', '=', $data['user_id']],['agent_id', '>', 0],['label', '=', 3]];
            $where3[]=[['start_time', 'between',[$data['start_time'],$data['end_time']] ],['agent_id', '>', 0],['label', '=', 3]];
            $where4[]=[['abank_account_num', '=', $data['bank_card']],['agent_id', '>', 0],['label', '=', 3]];
            $where5[]=[['agem_principals', '=', $data['realname']],['agent_id', '>', 0],['label', '=', 3]];

            $res=\db('cash_with')
                ->alias('cw')
                ->leftJoin('agent_bank ab',  'cw.c_id=ab.abank_cash_id')
                ->leftJoin('agent_manage am','cw.agent_id=am.agem_id')
                ->where($where)
                ->whereOr($where2)
                ->whereOr($where3)
                ->whereOr($where4)
                ->whereOr($where5)
                ->field('c_id,c_order,agem_id,agem_principals,start_time,money,abank_bank_name,abank_account_num,abank_name,c_status,c_remark')
                ->paginate(10,false,[
                'path'=>url('agents/getCash',['searchDetail'=>''])
            ]);

            $res2=$res->count();
        }else{
            $res=\db('cash_with')
                ->alias('cw')
                ->leftJoin('agent_bank ab',  'cw.c_id=ab.abank_cash_id')
                ->leftJoin('agent_manage am','cw.agent_id=am.agem_id')
                ->where('agent_id','>',0)
                ->where('cw.label',3)
                ->field('c_id,c_order,agem_id,agem_principals,start_time,money,abank_bank_name,abank_account_num,abank_name,c_status,c_remark')
                ->paginate(10,false,[
                    'path'=>url('agents/getCash')
                ]);
            $res2=$res->count();
        }
        $page=$res->render();

        $this->assign('start_time', $start_time);
        $this->assign('end_time',$end_time);
        $this->assign('status',$status);
        $this->assign('user_id',$user_id);
        $this->assign('realname',$realname);
        $this->assign('bank_card',$bank_card);


            $this->assign('list',$res);
            $this->assign('page',$page);
            $this->assign('count',$res2);

            return $this->fetch('agents/getCash');
        }

    /**
     * 提现查看
     * @return mixed
     */
    public  function getCashDetail(){
        $request=$this->request->param();
        $res=\db('cash_with')
            ->alias('cw')
            ->leftJoin('agent_bank ab',  'cw.c_id=ab.abank_cash_id')
            ->leftJoin('agent_manage am','cw.agent_id=am.agem_id')
            ->where('c_id',$request['c_id'])
            ->where('agem_id',$request['agem_id'])
            ->field('c_id,c_order,agem_id,agem_principals,agem_account,abank_bank_name,abank_account_num,abank_name,start_time,c_status,c_remark,money')
            ->find();
        $this->assign('list',$res);
        return $this->fetch();

    }

    /**
     * 提现状态修改
     * @return bool
     */
    public  function ajaxUpdateGetCash(){

        $request=$this->request->param();
        $data['c_id']=$request['id'];
        $data['c_status']=$request['status'];
        $data['c_remark']=$request['remark'];
        $data['end_time']=time();
        $model=new CashWithModel();
        $res=$model->isUpdate(true)->save($data,['c_id'=>$request['id']]);
        if(!$res){
            return false;
        }
        $this->ajaxReturn(['status'=>1,'msg'=>"修改成功",'url'=>('agenrts/getCash')]);


    }
    /**
     * 代理商汇款
     */
    public function remittance(){
        $searchDetail=$this->request;
        $searchData=$searchDetail->param();
        $start_time=$searchDetail->param('start_time');
        $end_time=$searchDetail->param('end_time');
        $status=$searchDetail->param('status');
        $user_id=$searchDetail->param('user_id');
        $realname=$searchDetail->param('realname');
        $bank_card=$searchDetail->param('bank_card');
       isset($searchData['status'])? $abank_status=$searchData['status']:$abank_status=0;
        if($searchDetail->isPost()){
            $data=$searchDetail->post();
            $data['start_time']=strtotime($data['start_time']);
            $data['end_time']=strtotime($data['end_time']);

            $where2[]=[['agem_id', '=', $data['user_id']],['agent_id', '>', 0],['abank_status', '=', $abank_status]];
            $where3[]=[['start_time', 'between',[$data['start_time'],$data['end_time']] ],['agent_id', '>', 0],['abank_status', '=', $abank_status]];
            $where4[]=[['abank_account_num', '=', $data['bank_card']],['agent_id', '>', 0],['abank_status', '=', $abank_status]];
            $where5[]=[['agem_principals', '=', $data['realname']],['agent_id', '>', 0],['abank_status', '=', $abank_status]];
            $res=\db('cash_with')
                ->alias('cw')
                ->leftJoin('agent_manage am','cw.agent_id=am.agem_id')
                ->leftJoin('agent_bank ab','cw.c_id=ab.abank_cash_id')
                ->where($where2)
                ->whereOr($where3)
                ->whereOr($where4)
                ->whereOr($where5)
                ->field('c_id,c_order,agem_id,end_time,agem_principals,start_time,money,abank_bank_name,abank_account_num,abank_name,c_status,c_remark,abank_status')
                ->paginate(10,false,[
                    'path'=>url('agents/remittance',['searchDetail'=>''])
                ]);
            $res2=$res->count();
        }else{
            $res=\db('cash_with')
                ->alias('cw')
                ->leftJoin('agent_manage am','cw.agent_id=am.agem_id')
                ->leftJoin('agent_bank ab','cw.c_id=ab.abank_cash_id')
                ->where('c_status',1)
                ->where('agent_id','>',0)
                ->where('abank_status',$abank_status)
                ->field('c_id,c_order,agem_id,end_time,agem_principals,start_time,money,abank_bank_name,abank_account_num,abank_name,c_status,c_remark,abank_status')
                ->paginate(10,false,[
                    'path'=>url('agents/remittance',['searchDetail'=>''])
                ]);
            $res2=$res->count();
        }
        $page=$res->render();

        $this->assign('start_time', $start_time);
        $this->assign('end_time',$end_time);
        $this->assign('user_id',$user_id);
        $this->assign('realname',$realname);
        $this->assign('bank_card',$bank_card);


        $this->assign('status',$abank_status);
        $this->assign('list',$res);
        $this->assign('page',$page);
        $this->assign('count',$res2);
//        return $this->fetch('agents/remittance');
        return $this->fetch();
    }



    }